import axios from "axios";

const { MP_ID, MP_SECRECT } = process.env;

// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
/**
 *
 * @param {*} js_code
 * @returns {Object} {unionid, openid, session_key}
 */
export async function code2Session(js_code) {
  const { data } = await axios.get(
    "https://api.weixin.qq.com/sns/jscode2session",
    {
      params: {
        appid: MP_ID,
        secret: MP_SECRECT,
        js_code,
        grant_type: "authorization_code",
      },
    }
  );
  if (data.errcode) {
    throw { msg: data.errmsg, code: data.errcode };
  }
  return data; //
}

let accessInfo = null;
export async function getAccessToken() {
  const now = Date.now();
  const needNew =
    !accessInfo || now - accessInfo.time >= accessInfo.expires_in * 1000;
  console.log({ accessInfo });
  if (needNew) {
    const { data } = await axios.get(
      "https://api.weixin.qq.com/cgi-bin/token",
      {
        params: {
          grant_type: "client_credential",
          appid: MP_ID,
          secret: MP_SECRECT,
        },
      }
    );
    data.time = now;
    accessInfo = data;
  }
  return accessInfo.access_token;
}

export async function getPhoneNumber(body) {
  const { code } = body;
  if (!code) {
    throw "未授权";
  }
  const token = await getAccessToken();
  const { data } = await axios.post(
    "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" +
      token,
    {
      code,
    }
  );
  if (data.errcode) {
    throw data.errmsg;
  }
  return data.phone_info; // {phoneNumber, purePhoneNumber}
}
